import React, { useState, useRef, useEffect, useCallback } from "react";
import { Select, Button, Space, message, Tabs } from "antd";
import "./GIS.css";
import { ZoomInOutlined, ZoomOutOutlined, FullscreenOutlined } from "@ant-design/icons";
import Breadcrumb from "../components/Breadcrumb";
import Earth3D, { EarthCanvasRef } from "../components/Earth3D";
import Earth2D, { Earth2DRef } from "../components/Earth2D";
import EarthPolarNew, { EarthPolarRef } from "../components/EarthPolarNew";
import EarthPiece, { EarthPieceRef } from "../components/EarthPiece";
import EarthGlb, { EarthGlbRef } from "../components/EarthGlb";
import DetailModal from "../components/DetailModal";
import GlobalDataTree from "../components/GISDetail/GlobalDataTree";
import PatrolDataTree from "../components/GISDetail/PatrolDataTree";
import FileListCard from "../components/GISDetail/FileListCard";
import { DataAreaFile, LatLngRect, LocationPoint, DetectionPointWithApiFields } from "../types/earth";
import request from "../utils/request";
import { getCorrectLngRange } from "../utils/earthUtils";
import { getPatrolInspectionAreaList, PatrolDetectionPoint, getPatrolDataSearchDetectionPointFile } from "../api/gis";

const { Option } = Select;

// 定义数据区域查询结果的文件类型
interface DataAreaResult {
  id: number;
  create_time: string;
  update_time: string;
  planet_id: number;
  task: string;
  task_zh: string;
  data_type: string;
  data_level: string;
  left_latitude: number;
  left_longitude: number;
  right_latitude: number;
  right_longitude: number;
  detection_name: string;
  detection_time: string;
  area_level?: string;
  area_name?: string;
  files: DataAreaFile[];
}

// 定义星球数据类型
interface Planet {
  id: number;
  create_time: string;
  update_time: string;
  planet_name: string;
  radius?: number;
  is_default?: number;
  planet_name_zh: string;
  origin_img?: string;
  output_img?: string;
  planet_img_level?: number;
  planet_img_size?: number;
}

// 归一化经纬度函数
const normalizeCoordinate = (value: number, isLatitude: boolean) => {
  if (isLatitude) {
    // 纬度归一化到 -90 到 90
    let normalized = value;
    while (normalized > 90) {
      normalized = 180 - normalized;
    }
    while (normalized < -90) {
      normalized = -180 - normalized;
    }
    return normalized;
  } else {
    // 经度归一化到 -180 到 180
    let normalized = value;
    while (normalized > 180) {
      normalized -= 360;
    }
    while (normalized < -180) {
      normalized += 360;
    }
    return normalized;
  }
};

// 格式化经纬度显示函数
const formatCoordinate = (value: number, isLatitude: boolean) => {
  const normalizedValue = normalizeCoordinate(value, isLatitude);
  const absValue = Math.abs(normalizedValue);
  const direction = isLatitude
    ? normalizedValue >= 0
      ? "N"
      : "S" // 纬度：正值北纬，负值南纬
    : normalizedValue >= 0
    ? "E"
    : "W"; // 经度：正值东经，负值西经

  return `${absValue.toFixed(4)}°${direction}`;
};

const GIS: React.FC = () => {
  const [viewMode, setViewMode] = useState<"3D" | "2D" | "polar" | "local">("3D");
  const [polarType, setPolarType] = useState<"north" | "south">("north");
  const [hoverCoord, setHoverCoord] = useState<{
    lat: number;
    lng: number;
  } | null>(null);
  const [clickedCoord, setClickedCoord] = useState<{
    lat: number;
    lng: number;
  } | null>(null);
  const [selectionRect, setSelectionRect] = useState<LatLngRect | null>(null); // 选区坐标信息
  const [selectedDetectionPoint, setSelectedDetectionPoint] = useState<DetectionPointWithApiFields | null>(null); // 新增探测点选择状态
  const [detailData, setDetailData] = useState<{
    type: "location" | "detection";
    data: LocationPoint | DetectionPointWithApiFields;
  } | null>(null); // 通用详情数据

  // 新增星球相关状态
  const [planets, setPlanets] = useState<Planet[]>([]);
  const [selectedPlanet, setSelectedPlanet] = useState<Planet | null>(null);

  // 新增查询模式状态
  const [queryMode, setQueryMode] = useState<"global" | "patrol">("global");

  // 新增选区模式状态 - 模拟Meta键按下
  const [isSelectionMode, setIsSelectionMode] = useState<boolean>(false);
  const isSelectionModeRef = useRef<boolean>(false);
  const queryModeRef = useRef<"global" | "patrol">("global");

  // 文件列表相关状态
  const [globalFiles, setGlobalFiles] = useState<DataAreaFile[]>([]);
  const [patrolFiles, setPatrolFiles] = useState<DataAreaFile[]>([]);

  // 将dataAreas和locationPoints放到state中
  const [dataAreas, setDataAreas] = useState<LatLngRect[]>([
    // 添加一些测试数据用于验证极地投影中的rects绘制
    // { minLat: 70, maxLat: 80, minLng: -50, maxLng: 50, name: "北极圈测试区域" },
    // { minLat: -80, maxLat: -70, minLng: -100, maxLng: 100, name: "南极圈测试区域" },
    // { minLat: 50, maxLat: 85, minLng: -60, maxLng: 120, name: "部分超出北极边界" },
    // { minLat: -85, maxLat: -50, minLng: -70, maxLng: 150, name: "部分超出南极边界" },
  ]);

  const [patrolAreas, setPatrolAreas] = useState<LatLngRect[]>([]);
  // 保存巡视区详细信息（用于获取base_img_level等信息）
  const [patrolInspectionAreas, setPatrolInspectionAreas] = useState<any[]>([]);
  const [previousViewMode, setPreviousViewMode] = useState<"3D" | "2D" | "polar" | "local">("3D");
  const [locationPoints, setLocationPoints] = useState<LocationPoint[]>([]);
  const [detectionPoints, setDetectionPoints] = useState<PatrolDetectionPoint[]>([]);
  const [selectedInspectionAreaId, setSelectedInspectionAreaId] = useState<number | null>(null);
  const showGLBModel = false;
  const earth2DRef = useRef<Earth2DRef>(null);
  const earth3DRef = useRef<EarthCanvasRef | EarthGlbRef>(null);
  const earthPieceRef = useRef<EarthPieceRef>(null);
  const earthPolarNorthRef = useRef<EarthPolarRef>(null);
  const earthPolarSouthRef = useRef<EarthPolarRef>(null);

  // 获取星球列表
  const fetchPlanets = async () => {
    try {
      const response = await request.get("/GIS/GISPlanet", {
        params: { planet_name: "" },
      });

      if (response.data?.code === 200) {
        const planetList = response.data.data.list;

        setPlanets(planetList);

        // 优先选择默认星球，如果没有默认星球则选择第一个
        if (planetList.length > 0) {
          const defaultPlanet = planetList.find((planet: any) => planet.is_default === 1);
          if (defaultPlanet) {
            setSelectedPlanet(defaultPlanet);
          } else {
            setSelectedPlanet(planetList[0]);
          }
        }
      }
    } catch (error) {
      console.error("获取星球列表失败:", error);
      message.error((error as any)?.message || "获取星球列表失败");
    }
  };

  // 处理Tree组件文件数据变化
  const handleTreeFileDataChange = (files: any[]) => {
    // 将文件数据转换为DataAreaResult格式，并确保经纬度为数字类型
    const results: DataAreaResult[] = files.map((file) => ({
      id: file.id,
      create_time: file.create_time,
      update_time: file.create_time,
      planet_id: selectedPlanet?.id || 0,
      task: file.task,
      task_zh: file.task,
      data_type: file.data_level,
      data_level: file.data_level,
      left_latitude: Number(file.left_latitude),
      left_longitude: Number(file.left_longitude),
      right_latitude: Number(file.right_latitude),
      right_longitude: Number(file.right_longitude),
      area_name: file.area_name || '',
      files: [
        {
          file_name: file.file_name,
          file_path: file.file_path,
          // 添加下载所需的必要参数
          id: file.id,
          data_type: file.data_type,
          product_id: file.product_id,
        },
      ],
    }));

    // 将查询结果转换为rects格式
    const newRects: LatLngRect[] = [];

    // 添加查询结果作为新的rects
    results.forEach((result: DataAreaResult) => {
      // 使用正确的经度范围计算函数处理跨越180度边界的情况
      const lngRange = getCorrectLngRange(result.left_longitude, result.right_longitude);

      newRects.push({
        minLat: Math.min(result.left_latitude, result.right_latitude),
        maxLat: Math.max(result.left_latitude, result.right_latitude),
        minLng: lngRange.minLng,
        maxLng: lngRange.maxLng,
        name: result.area_name,
        files: result.files, // 将files数据传入rects
      });
    });

    setDataAreas(newRects);

    // 清空之前的文件列表状态
    setGlobalFiles([]);
    setPatrolFiles([]);
    setSelectionRect(null);

    message.success(`查询成功，找到 ${results.length} 个数据区域`);
  };

  // 获取巡视数据文件（按巡视区查询）
  const fetchPatrolFileDataByArea = async (inspectionAreaId: number, dataSetName?: string) => {
    console.log('fetchPatrolFileDataByArea 被调用:', { inspectionAreaId, dataSetName, selectedPlanetId: selectedPlanet?.id });
    
    if (!inspectionAreaId || !selectedPlanet?.id) {
      console.log('参数检查失败，退出函数');
      return;
    }

    // 先切换到局部地图模式，给用户立即反馈
    setViewMode("local");

    // 保存当前选择的巡视区ID
    console.log('设置 selectedInspectionAreaId:', inspectionAreaId);
    setSelectedInspectionAreaId(inspectionAreaId);

    try {
      const response = await getPatrolDataSearchDetectionPointFile({
        planet_id: selectedPlanet.id,
        inspection_area_id: inspectionAreaId,
        data_set_name: dataSetName,
      });

      if (response.code === 200) {
        const detectionPoints: PatrolDetectionPoint[] = response.data;

        // 设置探测点数据
        setDetectionPoints(detectionPoints);

        message.success(`查询成功，找到 ${detectionPoints.length} 个探测点`);
      }
    } catch (error) {
      console.error("获取巡视数据文件失败:", error);
      message.error("获取巡视数据文件失败");
    }
  };

  // 处理巡视数据Tree组件节点点击
  const handlePatrolTreeNodeClick = (inspectionAreaId: number, dataSetName?: string) => {
    console.log('巡视区点击事件触发:', { inspectionAreaId, dataSetName });
    fetchPatrolFileDataByArea(inspectionAreaId, dataSetName);
  };

  // 获取巡视区列表
  const fetchPatrolInspectionAreas = async (planetId: number) => {
    try {
      const response = await getPatrolInspectionAreaList({
        planet_id: planetId,
        page: 1,
        page_size: 100,
      });

      if (response.code === 200) {
        // 保存完整的巡视区信息
        setPatrolInspectionAreas(response.data.list);

        // 将巡视区数据转换为地图显示格式
        const newPatrolRects: LatLngRect[] = response.data.list.map((area: any) => {
          // 使用正确的经度范围计算函数处理跨越180度边界的情况
          const lngRange = getCorrectLngRange(area.left_longitude, area.right_longitude);

          // 注意：这里需要包含巡视区的id，否则后续选中等逻辑无法关联
          return {
            id: area.id, // 巡视区唯一标识
            minLat: Math.min(area.left_latitude, area.right_latitude),
            maxLat: Math.max(area.left_latitude, area.right_latitude),
            minLng: lngRange.minLng,
            maxLng: lngRange.maxLng,
            name: area.inspection_area_name,
            files: [], // 巡视区暂时没有文件数据
            // 你也可以补充其他需要的字段，比如备注等
          };
        });

        setPatrolAreas(newPatrolRects);
        message.success(`成功获取 ${response.data.list.length} 个巡视区`);
      }
    } catch (error) {
      console.error("获取巡视区列表失败:", error);
      message.error("获取巡视区列表失败");
    }
  };

  // 获取地点数据
  const fetchLocationPoints = async (planetId: number) => {
    try {
      const response = await request.get("/GIS/GetLocationAll", {
        params: { planet_id: planetId },
      });

      if (response.data?.code === 200) {
        const locations = response.data.data;

        // 转换数据格式，将接口数据转换为测试数据格式
        const convertedLocations = locations.map((location: any) => ({
          id: location.id,
          planet_id: location.planet_id,
          name: location.location_name_zh, // 中文名作为name
          name_en: location.location_name, // 英文名作为name_en
          number: location.id.toString(), // 使用ID作为编号
          race: location.location_race,
          type: location.location_type,
          name_origin: location.location_name_origin,
          diameter: Number(location.location_diameter), // 转换为数字
          level: Number(location.location_level), // 转换为数字
          center_latitude: Number(location.center_latitude), // 转换为数字
          center_longitude: Number(location.center_longitude), // 转换为数字
        }));

        setLocationPoints(convertedLocations);
      }
    } catch (error) {
      console.error("获取地点数据失败:", error);
      message.error((error as any)?.message || "获取地点数据失败");
    }
  };

  // 处理星球选择变化
  const handlePlanetChange = (planetId: number) => {
    const planet = planets.find((p) => p.id === planetId);
    if (planet) {
      setSelectedPlanet(planet);
      // 清空之前的选择
      setLocationPoints([]); // 清空地点数据
      setDetectionPoints([]); // 清空探测点数据
      setDataAreas([]); // 清空数据区域
      setSelectionRect(null); // 清空选区
      // 清空巡视数据相关状态
      setDetectionPoints([]); // 清空探测点数据
      // 清空巡视区相关状态
      setPatrolAreas([]);
      // 清空详情数据
      setSelectedDetectionPoint(null);
      setDetailData(null);

      // 如果当前是local视图，切换星球时返回非local视图
      if (viewMode === "local") {
        setViewMode(previousViewMode || "3D");
      }

      // 重新获取数据
      fetchLocationPoints(planet.id);
    }
  };

  // 组件挂载时获取星球列表
  useEffect(() => {
    fetchPlanets();
  }, []);

  // 监听Meta键状态，模拟Meta键按下
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.metaKey && !isSelectionModeRef.current) {
        // 如果用户手动按下了Meta键，退出选区模式
        setIsSelectionMode(false);
        isSelectionModeRef.current = false;
      }
    };

    const handleKeyUp = (e: KeyboardEvent) => {
      if (!e.metaKey && isSelectionModeRef.current) {
        // 如果用户释放了Meta键，退出选区模式
        setIsSelectionMode(false);
        isSelectionModeRef.current = false;
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    document.addEventListener("keyup", handleKeyUp);

    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      document.removeEventListener("keyup", handleKeyUp);
    };
  }, []);

  // 当选中星球时，获取对应的数据
  useEffect(() => {
    if (selectedPlanet) {
      fetchLocationPoints(selectedPlanet.id);
    }
  }, [selectedPlanet]);

  // 监控queryMode变化
  useEffect(() => {
    //
    if (queryMode === "patrol" && selectedPlanet) {
      // 切换到巡视数据查询模式时，获取巡视区列表
      fetchPatrolInspectionAreas(selectedPlanet.id);
    }
  }, [queryMode, selectedPlanet]);

  // 处理坐标悬停
  const handleHover = (coord: { lat: number; lng: number } | null) => {
    // 防抖：坐标未变化时不更新，避免渲染风暴
    setHoverCoord((prev) => {
      if (prev === null && coord === null) return prev;
      if (prev && coord) {
        const sameLat = Math.abs(prev.lat - coord.lat) < 1e-4;
        const sameLng = Math.abs(prev.lng - coord.lng) < 1e-4;
        if (sameLat && sameLng) return prev;
      }
      return coord;
    });
  };

  // 处理坐标点击
  const handleClick = (coord: { lat: number; lng: number } | null) => {
    setClickedCoord(coord);
  };

  // 处理地点点击 - 统一处理两个组件的地点点击
  const handleLocationClick = (location: LocationPoint | null) => {
    if (location) {
      setDetailData({ type: "location", data: location });
    } else {
      setDetailData(null);
    }
  };

  // 关闭地点详情模态框
  const handleCloseLocationModal = () => {
    setDetailData(null);
  };

  // 处理探测点点击 - 新增
  const handleDetectionPointClick = (detectionPoint: DetectionPointWithApiFields | null) => {
    setSelectedDetectionPoint(detectionPoint);
    if (detectionPoint) {
      setDetailData({ type: "detection", data: detectionPoint });
    } else {
      setDetailData(null);
    }
  };
  const handleCloseDetectionPointModal = () => {
    setSelectedDetectionPoint(null);
    setDetailData(null);
  };

  // 处理巡视区点击 - 新增
  // 处理巡视区点击 - 保留原有逻辑，调用 fetchPatrolFileDataByArea 前依然设置巡视区ID和切换视图模式
  const handlePatrolAreaClick = (patrolArea: LatLngRect | null) => {
    if (patrolArea && (patrolArea as any).id !== undefined) {
      console.log('巡视区点击事件触发:', { patrolArea });

      // 保存当前巡视区 id
      setSelectedInspectionAreaId((patrolArea as any).id);

      // 保存当前视图模式以便之后返回
      setPreviousViewMode(viewMode);

      // 切换到局部地图模式
      setViewMode("local");

      // 执行数据获取逻辑（防止id类型不匹配，做一次 toString 转换以防接口类型问题）
      fetchPatrolFileDataByArea((patrolArea as any).id);
    }
  };

  // 处理巡视区悬停 - 新增
  const handlePatrolAreaHover = (patrolArea: LatLngRect | null) => {
    if (patrolArea) {
      //
    }
  };

  // 处理返回全局视图
  const handleBackToGlobal = () => {
    setViewMode(previousViewMode); // 返回到跳转到local模式前的视图模式
  };

  // 处理选区变化 - 统一处理两个组件的选区
  const handleSelectionChange = (selection: LatLngRect | null) => {
    // 避免重复设置相同的状态
    if (selection === null && selectionRect === null) {
      return;
    }
    setSelectionRect(selection);
  };

  // 处理放大
  const handleZoomIn = () => {
    if (viewMode === "3D") {
      // 3D视图放大
      earth3DRef.current?.zoomIn();
    } else if (viewMode === "2D") {
      // 2D视图放大
      earth2DRef.current?.zoomIn();
    } else if (viewMode === "polar") {
      // 极地视图放大
      if (polarType === "north") {
        earthPolarNorthRef.current?.zoomIn();
      } else {
        earthPolarSouthRef.current?.zoomIn();
      }
    } else if (viewMode === "local") {
      // 局部地图模式放大
      earthPieceRef.current?.zoomIn();
    }
  };

  // 处理缩小
  const handleZoomOut = () => {
    if (viewMode === "3D") {
      // 3D视图缩小
      earth3DRef.current?.zoomOut();
    } else if (viewMode === "2D") {
      // 2D视图缩小
      earth2DRef.current?.zoomOut();
    } else if (viewMode === "polar") {
      // 极地视图缩小
      if (polarType === "north") {
        earthPolarNorthRef.current?.zoomOut();
      } else {
        earthPolarSouthRef.current?.zoomOut();
      }
    } else if (viewMode === "local") {
      // 局部地图模式缩小
      earthPieceRef.current?.zoomOut();
    }
  };

  // 处理全图显示
  const handleFullView = () => {
    if (viewMode === "3D") {
      // 3D视图全图显示
      earth3DRef.current?.resetView();
    } else if (viewMode === "2D") {
      // 2D视图全图显示
      earth2DRef.current?.resetView();
    } else if (viewMode === "polar") {
      // 极地视图全图显示
      if (polarType === "north") {
        earthPolarNorthRef.current?.resetView();
      } else {
        earthPolarSouthRef.current?.resetView();
      }
    } else if (viewMode === "local") {
      // 局部地图模式重置视图
      earthPieceRef.current?.resetView();
    }
  };

  // 处理选区模式 - 模拟Meta键按下
  const handleSelectionMode = () => {
    if (isSelectionMode) {
      // 如果已经在选区模式，则退出
      setIsSelectionMode(false);
      isSelectionModeRef.current = false;
    } else {
      // 进入选区模式
      setIsSelectionMode(true);
      isSelectionModeRef.current = true;
    }
  };

  // 处理选区结束 - 统一处理两个组件的选区结束，选区完成后自动退出选区模式
  const handleSelectionEnd = useCallback(
    (selection: LatLngRect | null, intersectingRects: LatLngRect[], intersectingDetectionPoints: any[]) => {
      // 避免重复设置相同的状态
      if (selection === null && selectionRect === null) {
        return;
      }
      setSelectionRect(selection);

      const currentQueryMode = queryModeRef.current;

      if (currentQueryMode === "global") {
        // 全球数据查询模式 - 处理数据区域
        if (selection && intersectingRects && intersectingRects.length > 0) {
          // 收集所有相交区域的文件
          const allFiles: DataAreaFile[] = [];
          intersectingRects.forEach((rect) => {
            if (rect.files && rect.files.length > 0) {
              allFiles.push(...rect.files);
            }
          });

          if (allFiles.length > 0) {
            setGlobalFiles(allFiles);
            const areaName = intersectingRects[0].name || "未命名";
            message.success(`选中了数据区域"${areaName}"，包含 ${allFiles.length} 个文件`);
          } else {
            setGlobalFiles([]);
            message.info("选中的区域没有对应的数据文件");
          }
        } else {
          setGlobalFiles([]);
          if (selection) {
            message.info("选中的区域没有对应的数据文件");
          }
        }
      } else if (currentQueryMode === "patrol") {
        // 巡视数据查询模式 - 处理探测点
        if (selection && intersectingDetectionPoints && intersectingDetectionPoints.length > 0) {
          // 收集所有相交探测点的文件
          const allFiles: DataAreaFile[] = [];
          intersectingDetectionPoints.forEach((point) => {
            if (point.originalFiles && point.originalFiles.length > 0) {
              allFiles.push(...point.originalFiles);
            }
          });

          if (allFiles.length > 0) {
            setPatrolFiles(allFiles);
            message.success(`选中了 ${intersectingDetectionPoints.length} 个探测点，包含 ${allFiles.length} 个文件`);
          } else {
            setPatrolFiles([]);
            message.info("选中的探测点没有对应的数据文件");
          }
        } else {
          setPatrolFiles([]);
          if (selection) {
            message.info("选中的区域没有探测点");
          }
        }
      }

      // 选区完成后自动退出选区模式
      if (isSelectionModeRef.current) {
        setIsSelectionMode(false);
        isSelectionModeRef.current = false;
      }
    },
    []
  );

  return (
    <div className="gis-page" style={{ display: "flex", height: "calc(100vh - 145px)" }}>
      <aside
        style={{
          width: 420,
          background: "white",
          padding: 16,
          boxSizing: "border-box",
          overflowY: "auto",
        }}
      >
        <Breadcrumb text="" />
        <Select
          placeholder="请选择天体"
          allowClear
          value={selectedPlanet?.id}
          onChange={handlePlanetChange}
          style={{ width: "100%" }}
        >
          {planets.map((planet) => (
            <Option key={planet.id} value={planet.id}>
              {planet.planet_name_zh} ({planet.planet_name})
            </Option>
          ))}
        </Select>

        <Tabs
          style={{ marginTop: 10 }}
          defaultActiveKey="global"
          activeKey={queryMode}
          type="card"
          size="small"
          onChange={(key) => {
            const newMode = key as "global" | "patrol";
            setQueryMode(newMode);
            queryModeRef.current = newMode;

            // 如果当前是local视图，切换查询模式时返回非local视图
            if (viewMode === "local") {
              setViewMode(previousViewMode || "3D");
            }
          }}
          items={[
            {
              key: "global",
              label: "全球数据查询",
              children: (
                <div>
                  <GlobalDataTree planetId={selectedPlanet?.id || 0} onFileDataChange={handleTreeFileDataChange} />

                  {/* 文件列表显示区域 */}
                  <FileListCard
                    queryMode="global"
                    selectedPlanet={
                      selectedPlanet
                        ? { id: selectedPlanet.id, planet_name_zh: selectedPlanet.planet_name_zh }
                        : undefined
                    }
                    globalParams={{
                      selectedTask: "",
                      selectedLevel: "",
                    }}
                    noFilesMessage="已选中区域，但未找到对应的数据文件"
                    files={globalFiles}
                    hasSelection={!!selectionRect}
                  />
                </div>
              ),
            },
            {
              key: "patrol",
              label: "巡视数据查询",
              children: (
                <div>
                  <PatrolDataTree planetId={selectedPlanet?.id || 0} onNodeClick={handlePatrolTreeNodeClick} />

                  {/* 巡视数据文件列表显示区域 */}
                  <FileListCard
                    queryMode="patrol"
                    selectedPlanet={
                      selectedPlanet
                        ? { id: selectedPlanet.id, planet_name_zh: selectedPlanet.planet_name_zh }
                        : undefined
                    }
                    patrolParams={{
                      selectedDetectionTask: "",
                    }}
                    noFilesMessage="已选中区域，但未找到对应的探测点文件"
                    files={patrolFiles}
                    hasSelection={!!selectionRect}
                  />
                </div>
              ),
            },
          ]}
        />
      </aside>

      <main style={{ flex: 1, position: "relative" }}>
        {/* 全局地图模式 */}
        <div
          style={{
            visibility: "visible",
            width: "100%",
            height: "100%",
            position: "absolute",
            top: 0,
            left: 0,
          }}
        >
          <>
            {/* 视图切换控制 - 放在左上角 */}
            <div
              style={{
                position: "absolute",
                top: 16,
                left: 16,
                zIndex: 1000,
                background: "rgba(255, 255, 255, 0.9)",
                padding: 8,
                borderRadius: 6,
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
              }}
            >
              <Space direction="vertical" style={{ width: "100%" }}>
                {/* 返回按钮 - 只在局部地图模式下显示 */}
                {viewMode === "local" ? (
                  <Button onClick={handleBackToGlobal} size="small" type="text" style={{ width: "100%" }}>
                    ← 返回全局视图
                  </Button>
                ) : (
                  /* 视图切换按钮 - 只在全局地图模式下显示 */
                  <div style={{ display: "flex", gap: 8 }}>
                    <Button
                      type={viewMode === "3D" ? "primary" : "default"}
                      onClick={() => setViewMode("3D")}
                      style={{ flex: 1 }}
                      size="small"
                    >
                      3D视图
                    </Button>
                    <Button
                      type={viewMode === "2D" ? "primary" : "default"}
                      onClick={() => setViewMode("2D")}
                      style={{ flex: 1 }}
                      size="small"
                    >
                      2D视图
                    </Button>
                    <Button
                      type={viewMode === "polar" && polarType === "north" ? "primary" : "default"}
                      onClick={() => {
                        setPolarType("north");
                        setViewMode("polar");
                      }}
                      style={{ flex: 1 }}
                      size="small"
                    >
                      北极视图
                    </Button>
                    <Button
                      type={viewMode === "polar" && polarType === "south" ? "primary" : "default"}
                      onClick={() => {
                        setPolarType("south");
                        setViewMode("polar");
                      }}
                      style={{ flex: 1 }}
                      size="small"
                    >
                      南极视图
                    </Button>
                  </div>
                )}
              </Space>
            </div>

            {/* 选区控制 - 放在右上角 */}
            <div
              style={{
                position: "absolute",
                top: 16,
                right: 120,
                zIndex: 1000,
                background: "rgba(255, 255, 255, 0.9)",
                padding: 8,
                borderRadius: 6,
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
              }}
            >
              <Space direction="vertical" style={{ width: "100%" }}>
                <div style={{ display: "flex", gap: 4 }}>
                  <Button
                    onClick={handleSelectionMode}
                    size="small"
                    title="选区模式"
                    type={isSelectionMode ? "primary" : "default"}
                  >
                    选区
                  </Button>
                  <Button
                    onClick={() => {
                      // 先清空所有相关状态
                      setSelectionRect(null);
                      setGlobalFiles([]);
                      setPatrolFiles([]);
                      setIsSelectionMode(false);
                      isSelectionModeRef.current = false;

                      // 延迟调用组件的clearSelection方法，避免状态冲突
                      setTimeout(() => {
                        // 直接清空所有视图的选区
                        earth3DRef.current?.clearSelection();
                        earth2DRef.current?.clearSelection();
                        earthPieceRef.current?.clearSelection();
                      }, 0);
                    }}
                    size="small"
                    title="清空选区"
                    disabled={!selectionRect}
                  >
                    清空选区
                  </Button>
                </div>
              </Space>
            </div>

            {/* 缩放控制 - 放在右上角 */}
            <div
              style={{
                position: "absolute",
                top: 16,
                right: 16,
                zIndex: 1000,
                background: "rgba(255, 255, 255, 0.9)",
                padding: 8,
                borderRadius: 6,
                boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
              }}
            >
              <Space direction="vertical" style={{ width: "100%" }}>
                <div style={{ display: "flex", gap: 4 }}>
                  <Button icon={<ZoomInOutlined />} onClick={handleZoomIn} size="small" title="放大" />
                  <Button icon={<ZoomOutOutlined />} onClick={handleZoomOut} size="small" title="缩小" />
                  <Button icon={<FullscreenOutlined />} onClick={handleFullView} size="small" title="全图" />
                </div>
              </Space>
            </div>

            {/* 坐标信息显示 - 放在右下角 */}
            <div
              style={{
                position: "absolute",
                bottom: 16,
                right: 16,
                zIndex: 1000,
                background: "rgba(0, 0, 0, 0.7)",
                color: "white",
                padding: 12,
                borderRadius: 6,
                minWidth: 200,
                fontSize: 12,
              }}
            >
              <div style={{ marginBottom: 8, fontWeight: "bold", fontSize: 14 }}>坐标信息</div>
              {hoverCoord && (
                <div style={{ marginBottom: 8 }}>
                  <strong>悬停位置：</strong>
                  <br />
                  {formatCoordinate(hoverCoord.lat, true)}, {formatCoordinate(hoverCoord.lng, false)}
                </div>
              )}
              {clickedCoord && (
                <div style={{ marginBottom: 8 }}>
                  <strong>点击位置：</strong>
                  <br />
                  {formatCoordinate(clickedCoord.lat, true)}, {formatCoordinate(clickedCoord.lng, false)}
                </div>
              )}
              {selectionRect && (
                <div style={{ marginBottom: 8 }}>
                  <strong>选区坐标：</strong>
                  <br />
                  {formatCoordinate(selectionRect.minLat, true)}~{formatCoordinate(selectionRect.maxLat, true)}
                  <br />
                  {formatCoordinate(selectionRect.minLng, false)}~{formatCoordinate(selectionRect.maxLng, false)}
                </div>
              )}
              {selectedDetectionPoint && (
                <div style={{ marginBottom: 8 }}>
                  <strong>选中探测点：</strong>
                  <br />
                  {selectedDetectionPoint.name}
                  <br />
                  {formatCoordinate(selectedDetectionPoint.center_latitude, true)},{" "}
                  {formatCoordinate(selectedDetectionPoint.center_longitude, false)}
                  <br />
                  任务类型: {selectedDetectionPoint.task_type}
                </div>
              )}
              {!hoverCoord && !clickedCoord && !selectionRect && !selectedDetectionPoint && (
                <div style={{ color: "#ccc", fontStyle: "italic" }}>移动鼠标查看坐标信息</div>
              )}
            </div>

            {!showGLBModel && selectedPlanet && (
              <>
                <div
                  style={{
                    visibility: viewMode === "3D" ? "visible" : "hidden",
                    width: "100%",
                    height: "100%",
                    position: "absolute",
                    top: 0,
                    left: 0,
                  }}
                >
                  <Earth3D
                    modelUrl={
                      false &&
                      ("/uploads_files_4462300_Astreoid-1.glb" ||
                        "https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf")
                    }
                    radius={selectedPlanet?.radius || 0}
                    tileUrlTemplate={request.getUrl(
                      `/GIS/GISPlanetGetTile?planet_id=${selectedPlanet.id}&tile_tag=planet&level={z}&row={y}&col={x}`
                    )}
                    maxZoom={selectedPlanet.planet_img_level || 5}
                    dataAreas={queryMode === "global" ? dataAreas : []}
                    patrolAreas={queryMode === "patrol" ? patrolAreas : []}
                    locationPoints={locationPoints}
                    onHover={handleHover}
                    onClick={handleClick}
                    onLocationClick={handleLocationClick}
                    onPatrolAreaClick={handlePatrolAreaClick}
                    onPatrolAreaHover={handlePatrolAreaHover}
                    onSelectionChange={handleSelectionChange}
                    onSelectionEnd={handleSelectionEnd}
                    externalSelection={selectionRect}
                    simulatedMetaKey={isSelectionMode}
                    ref={earth3DRef}
                  />
                </div>

                <div
                  style={{
                    visibility: viewMode === "2D" ? "visible" : "hidden",
                    width: "100%",
                    height: "100%",
                    position: "absolute",
                    top: 0,
                    left: 0,
                  }}
                >
                  <Earth2D
                    dataAreas={queryMode === "global" ? dataAreas : []}
                    patrolAreas={queryMode === "patrol" ? patrolAreas : []}
                    locationPoints={locationPoints}
                    tileUrlTemplate={request.getUrl(
                      `/GIS/GISPlanetGetTile?planet_id=${selectedPlanet.id}&tile_tag=planet&level={z}&row={y}&col={x}`
                    )}
                    maxZoom={selectedPlanet.planet_img_level || 5}
                    radius={selectedPlanet?.radius || 0}
                    onHover={handleHover}
                    onClick={handleClick}
                    onLocationClick={handleLocationClick}
                    onPatrolAreaClick={handlePatrolAreaClick}
                    onPatrolAreaHover={handlePatrolAreaHover}
                    onSelectionEnd={handleSelectionEnd}
                    onSelectionChange={handleSelectionChange}
                    externalSelection={selectionRect}
                    simulatedMetaKey={isSelectionMode}
                    ref={earth2DRef}
                  />
                </div>

                {/* 北极视图 */}
                <div
                  style={{
                    visibility: viewMode === "polar" && polarType === "north" ? "visible" : "hidden",
                    width: "100%",
                    height: "100%",
                    position: "absolute",
                    top: 0,
                    left: 0,
                  }}
                >
                  <EarthPolarNew
                    ref={earthPolarNorthRef}
                    polarType="north"
                    tileUrlTemplate={request.getUrl(
                      `/GIS/GISPlanetGetTile?planet_id=${selectedPlanet.id}&tile_tag=north&level={z}&row={y}&col={x}`
                    )}
                    maxZoom={selectedPlanet?.planet_img_level || 5}
                    locationPoints={locationPoints}
                    dataAreas={queryMode === "global" ? dataAreas : []}
                    patrolAreas={queryMode === "patrol" ? patrolAreas : []}
                    onCoordinateClick={handleClick}
                    onCoordinateHover={handleHover}
                    onLocationClick={handleLocationClick}
                    onRectClick={(rect) => {
                      // 可以在这里添加矩形区域点击的处理逻辑
                    }}
                    onPatrolAreaClick={handlePatrolAreaClick}
                    onPatrolAreaHover={handlePatrolAreaHover}
                    onSelectionChange={handleSelectionChange}
                    onSelectionEnd={handleSelectionEnd}
                    externalSelection={selectionRect}
                    simulatedMetaKey={isSelectionMode}
                  />
                </div>

                {/* 南极视图 */}
                <div
                  style={{
                    visibility: viewMode === "polar" && polarType === "south" ? "visible" : "hidden",
                    width: "100%",
                    height: "100%",
                    position: "absolute",
                    top: 0,
                    left: 0,
                  }}
                >
                  <EarthPolarNew
                    ref={earthPolarSouthRef}
                    polarType="south"
                    tileUrlTemplate={request.getUrl(
                      `/GIS/GISPlanetGetTile?planet_id=${selectedPlanet.id}&tile_tag=south&level={z}&row={y}&col={x}`
                    )}
                    maxZoom={selectedPlanet?.planet_img_level || 5}
                    locationPoints={locationPoints}
                    dataAreas={queryMode === "global" ? dataAreas : []}
                    patrolAreas={queryMode === "patrol" ? patrolAreas : []}
                    onCoordinateClick={handleClick}
                    onCoordinateHover={handleHover}
                    onLocationClick={handleLocationClick}
                    onRectClick={(rect) => {
                      // 可以在这里添加矩形区域点击的处理逻辑
                    }}
                    onPatrolAreaClick={handlePatrolAreaClick}
                    onPatrolAreaHover={handlePatrolAreaHover}
                    onSelectionChange={handleSelectionChange}
                    onSelectionEnd={handleSelectionEnd}
                    externalSelection={selectionRect}
                    simulatedMetaKey={isSelectionMode}
                  />
                </div>

                {/* 局部地图视图 */}
                <div
                  style={{
                    visibility: viewMode === "local" ? "visible" : "hidden",
                    width: "100%",
                    height: "100%",
                    position: "absolute",
                    top: 0,
                    left: 0,
                  }}
                >
                  {selectedInspectionAreaId &&
                    (() => {
                      // 查找当前巡视区的信息以获取base_img_level和经纬度范围
                      const currentArea = patrolInspectionAreas.find((area) => area.id === selectedInspectionAreaId);
                      const maxLevel = currentArea?.base_img_level || 5;

                      // 构建经纬度范围对象
                      const latLngBounds = currentArea
                        ? {
                            minLat: Math.min(currentArea.left_latitude, currentArea.right_latitude),
                            maxLat: Math.max(currentArea.left_latitude, currentArea.right_latitude),
                            minLng: Math.min(currentArea.left_longitude, currentArea.right_longitude),
                            maxLng: Math.max(currentArea.left_longitude, currentArea.right_longitude),
                          }
                        : undefined;

                      return (
                        <EarthPiece
                          ref={earthPieceRef}
                          detectionPoints={detectionPoints}
                          tileUrlTemplate={request.getUrl(
                            `/GIS/GISPlanetGetTile?planet_id=${selectedPlanet.id}&tile_tag=inspection&inspection_area_id=${selectedInspectionAreaId}&level={z}&row={y}&col={x}`
                          )}
                          maxLevel={maxLevel}
                          latLngBounds={latLngBounds}
                          onCoordinateClick={handleClick}
                          onCoordinateHover={handleHover}
                          onDetectionPointClick={(point) => {
                            if (point) {
                              // 当点击探测点时，收集该点的所有数据文件并设置到patrolFiles
                              if (point.data_set_list && point.data_set_list.length > 0) {
                                const files = point.data_set_list;
                                setPatrolFiles([...files]);
                                message.success(`选中了 ${files.length} 个相关文件`);
                              } else {
                                setPatrolFiles([]);
                                message.info("该探测点没有相关的数据文件");
                              }

                              setSelectionRect(null);
                            }
                          }}
                          onDetectionPointHover={() => {
                            // 可以在这里添加探测点悬停提示
                          }}
                          onSelectionEnd={(selectionRect, intersectingDetectionPoints) => {
                            // 处理选区结果
                            if (selectionRect) {
                              setSelectionRect(selectionRect);
                              // 收集所有相交探测点的文件
                              const allFiles: DataAreaFile[] = [];
                              intersectingDetectionPoints.forEach((point) => {
                                if (point.data_set_list && point.data_set_list.length > 0) {
                                  allFiles.push(...point.data_set_list);
                                }
                              });

                              if (allFiles.length > 0) {
                                setPatrolFiles(allFiles);
                                message.success(
                                  `选中了 ${intersectingDetectionPoints.length} 个探测点，包含 ${allFiles.length} 个文件`
                                );
                              } else {
                                setPatrolFiles([]);
                                message.info("选中的探测点没有对应的数据文件");
                              }

                              // 选区完成后自动退出选区模式
                              setIsSelectionMode(false);
                              isSelectionModeRef.current = false;
                            }
                          }}
                          simulatedMetaKey={isSelectionMode}
                        />
                      );
                    })()}
                </div>
              </>
            )}

            {!selectedPlanet && (
              <div
                style={{
                  width: "100%",
                  height: "100%",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  background: "#f5f5f5",
                  color: "#666",
                  fontSize: 16,
                }}
              >
                请先选择天体
              </div>
            )}

            {showGLBModel && (
              <div
                style={{
                  visibility: "visible",
                  width: "100%",
                  height: "100%",
                  position: "absolute",
                  top: 0,
                  left: 0,
                }}
              >
                <EarthGlb
                  modelUrl={"/scene.glb"}
                  radius={selectedPlanet?.radius || 0}
                  rects={queryMode === "global" ? dataAreas : []}
                  locationPoints={locationPoints}
                  detectionPoints={queryMode === "patrol" ? (detectionPoints as any) : []}
                  onHover={handleHover}
                  onClick={handleClick}
                  onLocationClick={handleLocationClick}
                  onDetectionPointClick={handleDetectionPointClick as any}
                  onSelectionChange={handleSelectionChange}
                  onSelectionEnd={handleSelectionEnd}
                  externalSelection={selectionRect}
                  simulatedMetaKey={isSelectionMode}
                  ref={earth3DRef}
                />
              </div>
            )}
          </>
        </div>

        {detailData && (
          <DetailModal
            detailData={detailData}
            onClose={() => {
              if (detailData.type === "location") {
                handleCloseLocationModal();
              } else {
                handleCloseDetectionPointModal();
              }
            }}
          />
        )}
      </main>
    </div>
  );
};

export default GIS;
